<script setup lang="ts">
import Nifi from "../../nifi";
import { computed, reactive, ref } from "vue";
import { ElSelectV2, ElButton, ElInput, ElTable, ElTableColumn, ElTooltip, ElIcon, ElPagination, ElMessage } from "element-plus"
import { chunk, intersection } from "lodash-es"
import {t} from "../../i18n/index"
//
const emits = defineEmits<{finish:[boolean|string]}>();
const { nifi, groupId } = defineProps<{ nifi: Nifi, groupId: string }>();

const pages = reactive({ pageNum: 1, pageSize: 10, total: 0, sizes: [10,20,50], layout: "prev, pager, next, total" })
const groups = reactive<any[]>([])
const tags = reactive(new Set<string>())

const query = ref("");
const group = ref<string[]>([]);
const tag = ref<string[]>([]) // 标签选择
const list = reactive<any[]>(nifi.flow.controllerServiceTypes);
// 初始化数据
for (const row of list) {
    if (!groups.includes(row.bundle.group)) {
        groups.push(row.bundle.group)
    }
    if (row.tags && row.tags.length > 0) {
        row.tags.map((v: string) => tags.add(v))
    }
}
//
const flist = computed(() => {
    let t = list;
    if (query.value) {
        t = t.filter(d => d.type.toLowerCase().indexOf(query.value.toLowerCase()) != -1)
    }
    if (group.value.length > 0) {
        t = t.filter(d => group.value.includes(d.bundle.group))
    }
    if (tag.value.length > 0) {
        t = t.filter(d => intersection(d.tags, tag.value).length > 0)
    }
    pages.total = t.length;
    return t;
})

const plist = computed(() => {
    const l = flist.value;
    return chunk(l, pages.pageSize)
})

const data = computed(() => plist.value[pages.pageNum - 1] || [])
//
const currentRow = ref<any>()
//
const clearQuery = () => {
    query.value = "";
    group.value = [];
    tag.value = [];
}

const getContent = (explicitRestrictions = []) => {
    const c = explicitRestrictions.map((d: any) => `<li> ${d?.requiredPermission?.label} - ${d.explanation} </li>`).join(' ')
    return `<ul>${c}</ul>`
}
const getApiContent = (controllerServiceApis = []) => {
    const c = controllerServiceApis.map((d: any) => `<li> ${d?.type.split('.').pop()} ${d.bundle.version} ${d.bundle.group} - ${d.bundle.artifact} </li>`).join(' ')
    return `<ul>${c}</ul>`
}

// 获取 类型并初始化数据
const getType = (row: any) => row.type.split('.').pop();
//
const handleReset = () => {
    clearQuery()
}

const handleRowClick = (row: any) => {
    currentRow.value = row;
}

const handleCancel = () => {
    emits('finish',true)
}

const handleSubmit = async () => {
    const row = currentRow.value;
    if (!row) {
        ElMessage.warning(t('cs-new-select-type'))
        return false;
    }

    const d = {
        component: {
            name: row.type.split('.').pop(),
            type: row.type,
            bundle: row.bundle
        }
    }

    const res = await nifi.ControlService.add(d,groupId)
    //
    emits('finish',res === false ? false : res.id)
}

</script>

<template>
    <div class="w-50vw h-50vh min-h-500px min-w-800px flex flex-col gap-8px">
        <div class="flex items-center gap-10px h-40px">
            <b class="truncate min-w-120px">{{t('cs-new-text')}}</b>
            <ElSelectV2 v-model="group" :options="groups.map(v => ({ label: v, value: v }))" :placeholder="t('cs-new-group-placeholder')"
                multiple collapse-tags :teleported="false" >
            </ElSelectV2>
            <ElSelectV2 v-model="tag" :options="Array.from(tags).map(v => ({ label: v, value: v }))" :placeholder="t('cs-new-tag-placeholder')"
                filterable multiple collapse-tags :teleported="false" >
            </ElSelectV2>
            <ElInput v-model="query" :placeholder="t('cs-new-query-placeholder')"></ElInput>

            <ElButton @click="handleReset" type="info" plain >{{t('cs-new-reset')}}</ElButton>
            <ElButton @click="handleCancel" type="primary" plain>{{t('box-cancel-text')}}</ElButton>
            <ElButton @click="handleSubmit" type="primary" >{{t('box-submit')}}</ElButton>
        </div>
        <div class="flex-1 overflow-hidden">
            <ElTable class=":uno: w-full important-h-full" :data="data" stripe highlight-current-row
                @row-click="handleRowClick">

                <ElTableColumn width="50">
                    <template #default="{ row }">
                        <ElTooltip v-if="row?.explicitRestrictions?.length > 0"
                            :content="getContent(row.explicitRestrictions)" :raw-content="true">
                            <el-icon>
                                <i class="i-fluent-color:warning-16 w-1em h-1em"></i>
                            </el-icon>
                        </ElTooltip>
                    </template>
                </ElTableColumn>
                <ElTableColumn :label="t('cs-new-table-index')" width="80">
                    <template #default="{ $index }">{{ pages.pageSize * (pages.pageNum - 1) + $index + 1 }}</template>
                </ElTableColumn>
                <ElTableColumn :label="t('cs-new-table-type')" show-overflow-tooltip width="300">
                    <template #default="{ row }">{{ getType(row) }}</template>
                </ElTableColumn>
                <ElTableColumn :label="t('cs-new-table-version')" show-overflow-tooltip width="120">
                    <template #default="{ row }">
                        <span>{{ row.bundle.version }}</span>
                        <ElTooltip :content="getApiContent(row.controllerServiceApis)" :raw-content="true">
                            <ElIcon>
                                <Info />
                            </ElIcon>
                        </ElTooltip>
                    </template>
                </ElTableColumn>
                <ElTableColumn :label="t('cs-new-table-tab')" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ row.tags?.join(',') }}
                    </template>
                </ElTableColumn>

            </ElTable>
        </div>
        <div class="flex justify-end h-40px">
            <ElPagination v-model:current-page="pages.pageNum" v-model:page-size="pages.pageSize"
                :page-sizes="pages.sizes" :total="pages.total" :layout="pages.layout" ></ElPagination>
        </div>
    </div>
</template>

<style>

</style>